// var DB = require("../lib/db_pg").DB;
var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var http_request = require('../lib/util.js').http_request;
var md5Salt = require('../lib/util').md5Salt;

exports.login = function(req, res){
  var user_name = req.param('user_name');
  var user_password = req.param('user_password');

  if (!user_name || !user_password){
    return resErr(res, '请输入用户名和密码');
  }

  req.session.user = null;
  user_password = md5Salt(user_password);
  console.log(user_password);
  var db = new DB();
  async.waterfall([function(cb){
    var sql_text = "select * from t_hotel_user where user_name = ? and password = ? and active = 1";

    var params = [];
    params.push(user_name);
    params.push(user_password);

    db.query(sql_text, params, function(err, data){
      if(err)
        return cb(err);
      // console.log(data.legnth);
      if(data.length){
        req.session.user = data[0];
        req.session.user_role = data[0].user_role;
        console.log(req.session.user_role);
      }
      // console.log(req.session.user);
      // console.log(data);
      // console.log(data.length);
      return cb(null);
    });
  }], function(err){
    if(err){
      console.log(err);
      return resErr(res, err);
    }
    if(req.session.user){
      return res.jsonp({success: true});
    }else{
      return resErr(res, '用户名或密码错误');
    }
  });
}


exports.adminuser_logout = function(req,res) {
  if(req.session.adminuser)
    req.session.adminuser = null;
  if(req.session)
    req.session.destroy();
  // return res.json({success:true,msg:'退出成功！'});
  // console.log('logout');
  return res.redirect('/login');
}

//生成树结构数组
function getResourceTree(datas) {
  if(datas) {
    var root_children_list = [];
    for(var i=0;i<datas.length;i++) {
      var childlist = datas[i].sub_categorys;
      var child = {};
      if(childlist) {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = false;
        child.icon = datas[i].icon;
        child.children = getResourceTree(childlist);
        root_children_list.push(child);
      } else {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = true;
        child.icon = datas[i].icon;
        child.hrefTarget = datas[i].res_url;
        root_children_list.push(child);
      }
    }
    return root_children_list;
  } else {
    return null;
  }
}

exports.get_users = function(req, res){
	async.waterfall([function(cb){
		var sql_text = "select * from t_hotel_user where 1 = 1";
		var db = new DB();

		db.query(sql_text, [], function(err, data){
			if(err) return cb(err);
			return res.jsonp(data);
		});
	}], function(err){
		if(err) return resErr(res, err);
		return res.json({
			success: true
		});
	});
}

exports.get_user = function(req, res){
	var user_name = req.param('user_name');

	if(!user_name){
		return res.jsonp({
			success: false,
			msg: '用户名不能为空'
		})
	}

	async.waterfall([function(cb){
		var sql_text = "select * from t_hotel_user where 1 = 1 and user_name = ?";

		var params = [];
		params.push(user_name);
		var db = new DB();

		db.query(sql_text, params, function(err, data){
			if(err) return cb(err);
			return res.jsonp(data);
		});
	}], function(err){
		if(err) return resErr(res, err);
		return res.json({
			success: true
		});
	});
}

exports.save_user = function(req, res){
  var origin_user_name = req.param('origin_user_name');
  var user_name = req.param('user_name');
  var user_realname = req.param('user_realname');
  var user_role = req.param('user_role');
  var active = req.param('active');
  var password = req.param('password');

  console.log(user_role);

  var db = new DB();

  async.series([function(cb){
    // console.log('第一层');
    if(origin_user_name == user_name) return cb(null, null)
    var sql_text = "select * from t_hotel_user where user_name = ?";

    var params = [];
    params.push(user_name);

    db.query(sql_text, params, function(err, data){
      if(err) return cb(err);
      console.log(data.length);
      if(data.length > 0){
        console.log('该用户名已存在');
        return cb('该用户名已存在', null);
      }else{
        console.log('该用户名不存在');
        return cb(null, null);
      }
    })

  }, function(cb){
    // console.log('第二层');
    // console.log(err);
    // if(err) return cb(err);
    var sql_text = "update t_hotel_user set user_name = ?, user_realname = ?, user_role = ?, active = ?";
    if(password) sql_text += ", password = ?";

    sql_text += " where user_name = ?";

    var params = [];
    params.push(user_name);
    params.push(user_realname);
    params.push(user_role);
    params.push(active);
    if(password){
      password = md5Salt(password);
      params.push(password);
    }
    params.push(origin_user_name);

    db.query(sql_text, params, function(err, data){
      if(err){
        return cb(err, null);
      }else{
        return cb(null, null);
      }
    })
  }], function(err, result){
    // console.log('错误');
    // console.log(err);
    if(err) return res.jsonp({
      success: false,
      msg: err
    })
    return res.json({
      success: true,
      msg: null
    })
  })
}

exports.add_user = function(req, res){
  var user_name = req.param('user_name');
  var user_realname = req.param('user_realname');
  var user_role = req.param('user_role');
  var active = req.param('active');
  var password = req.param('password');

  // console.log(user_role);

  var db = new DB();

  async.series([function(cb){
    var sql_text = "select * from t_hotel_user where user_name = ?";

    var params = [];
    params.push(user_name);

    db.query(sql_text, params, function(err, data){
      if(err) return cb(err);
      // console.log(data.length);
      if(data.length > 0){
        // console.log('该用户名已存在');
        return cb('该用户名已存在', null);
      }else{
        // console.log('该用户名不存在');
        return cb(null, null);
      }
    })

  }, function(cb){
    var sql_text = "insert into t_hotel_user(user_name, user_realname, user_role, active, password) values(?, ?, ?, ?, ?);"

    var params = [];
    params.push(user_name);
    params.push(user_realname);
    params.push(user_role);
    params.push(active);
      
    password = md5Salt(password);
    params.push(password);

    db.query(sql_text, params, function(err, data){
      if(err){
        return cb(err, null);
      }else{
        return cb(null, null);
      }
    })
  }], function(err, result){
    // console.log('错误');
    // console.log(err);
    if(err) return res.jsonp({
      success: false,
      msg: err
    })
    return res.json({
      success: true,
      msg: null
    })
  })
}

exports.my_user_role = function(req, res){
  return res.jsonp({
    role: req.session.user_role? req.session.user_role : ''
  })
}